package org.rcy.framework.thrift.serializer;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.rcy.framework.thrift.metadata.FieldValueMetaData;
import org.rcy.framework.thrift.metadata.JavaType;

import java.util.HashMap;
import java.util.Map;

/**
 * 实现Thrift对象的序列化和反序列化
 * 
 * @author zhouree
 */
public class ThriftSerializer {

	private static Map<JavaType, Serializer> serializers = new HashMap();

	static {
		serializers.put(JavaType.BASIC, new BasicSerializer());
		serializers.put(JavaType.DATE, new DateSerializer());
		serializers.put(JavaType.ENUM, new EnumSerializer());
		serializers.put(JavaType.LIST, new ListSerializer());
		serializers.put(JavaType.MAP, new MapSerializer());
		serializers.put(JavaType.SET, new SetSerializer());
		serializers.put(JavaType.EXCEPTION, new ExceptionSerializer());
		serializers.put(JavaType.STRUCT, new StructSerializer());
		serializers.put(JavaType.BINARY, new BinarySerializer());
	}

	public static Object read(TProtocol iprot, FieldValueMetaData valueMetaData) throws TException {
		JavaType javaType = valueMetaData.javaType;
		if (javaType == null) {
			return null;
		}
		return serializers.get(javaType).read(iprot, valueMetaData);
	}

	public static void write(TProtocol oprot, FieldValueMetaData valueMetaData, Object value) throws TException {
		JavaType javaType = valueMetaData.javaType;
		if (javaType == null) {
			return;
		}
		serializers.get(javaType).write(oprot, valueMetaData, value);
	}

}
